import { Controller, Get, HttpException, HttpStatus, Post, StreamableFile, UploadedFile, UseInterceptors } from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Result } from 'src/utils/Result';
import { CosStorage } from 'src/utils/cos.storage';
import { config } from 'src/utils/generate.secretkey';
import { createReadStream } from 'fs';
import { join } from 'path';
import { ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
import { FileUploadDto } from './dto/file.upload.dto ';
@ApiTags('文件上传')
@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}
  @Get('file')
  test(): StreamableFile {
    const file = createReadStream(join(process.cwd(), '前端开发简历.docx'));
    return new StreamableFile(file)
  }
  @ApiOperation({ description: '单图片上传' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: 'List of cats',
    type: FileUploadDto,
  })
  @UseInterceptors(FileInterceptor('file', {
    storage: CosStorage.register({
      SecretId: config.secretId,
      SecretKey: config.secretKey,
    })
    // storage: CosStorage.register({
    //   onCredentials: (cb) => {
    //     new GenerateSecretkey().getCredential((err, res) => {
    //       if(err) cb(err)
    //       cb(null, res)
    //     })
    //   }
    // })
  }))
  @Post('cos')
  async cosUpload(@UploadedFile() File) {
    try {
        return Result.success(File.url) // 返回上传成功后的URL
    } catch (err) {
        throw new HttpException(err.message, HttpStatus.BAD_REQUEST);
    }
  }
  @Post('album')
  @UseInterceptors(FileInterceptor('file'))
  upload (@UploadedFile() file) {
    return Result.success(`http://127.0.0.1:3000/images/${file.filename}`)
  }
}
